package com.google.project.client.ProjectManager;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.ScrollPanel;

public class Gantt extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button button;
	@UiField Button button_1;
	@UiField Button btnListOfTask;
	@UiField Label lblProject;
	
	@UiField ScrollPanel ganttPanel;
	@UiField Label lblStartDate;
	@UiField Label lblDueDATE;
	@UiField Label lblFinishDate;
	@UiField Label lblComplete;
	@UiField Button btnAssignTask;

	private final ProjectServiceAsync projectService = GWT
			.create(ProjectService.class);
	private final ProjTaskServiceAsync ProjectTaskService = GWT.create(ProjTaskService.class);
	interface Binder extends UiBinder<Widget, Gantt> {
	}

	private String projectId;
	int count = 0;
	int load =0;
	int numOfMile = 0; 
	public Gantt() {
		initWidget(binder.createAndBindUi(this));
		
	}

	public Gantt(String projectId) {
		initWidget(binder.createAndBindUi(this));
		HTML html = new HTML("<div id='Gantt'></div>");
		ganttPanel.add(html);
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	button.setFocus(true);
	        }
	    });
		this.projectId = projectId;
		projectService.getProjectById(projectId,
				new AsyncCallback<ProjectDTO>() {

					@Override
					public void onSuccess(ProjectDTO result) {
						// TODO Auto-generated method stub

						lblProject.setText("Dự án : " + result.getProjectName());
						lblComplete.setText("Hoàn thành : "+result.getComplete()+" (%)");
						lblStartDate.setText("Ngày bắt đầu:"+CommonFuntion.convertToDate(new Date(result.getStartDate())));
						lblDueDATE.setText("KT dự kiến:"+CommonFuntion.convertToDate(new Date(result.getDueDate())));
						if(result.getStatus()==2||result.getStatus()==3)
						{
							lblFinishDate.setText("KT thực tế:"+CommonFuntion.convertToDate(new Date(result.getFinishDate())));
						}else
						{
							lblFinishDate.setText("");
						}
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
	}

	private native void smile(String data)
	/*-{
		$wnd.smile(data);
	}-*/;

	private native void drawGantt(String data)
	/*-{
		$wnd.smile(data);
	}-*/;

	public String convertToDate(Date input) {
		return (input.getMonth() + 1) + "/" + input.getDate() + "/"
				+ (input.getYear() + 1900);

	}
	
	
	String drawRowChart(ProjectTaskDTO task)
	{
		String a ="";
		
		int taskId = task.getTaskId();
		String taskName = task.getTaskName();
		String startDate = convertToDate(new Date(task.getStartDate()));
		String endDate = convertToDate(new Date(task.getDueDate()));
		String color="";
	if(task.getStatus()!=3)
		{
		 color ="00ffff";
		}
	else
	{
		 color ="ff0000";
	}
		
		String link ="";
		int isMile = task.getIsMile();
//		String res = "ducnm";
//		int comp = 60;
		
		String res =task.getOptAccountName();
		
	    Double total =task.getAmountOfWork();
	    Double finish = task.getFinishedWork();
	    Double complete=0d;
	    if(task.getIsMile()==0)
	    {
	    	 complete = (finish/total)*100;
		
	    }

		int group = task.getGroup();
		int parent = task.getParentId();
		int open =1;
		String depen ="";
		
		
	   if(task.getDependent()!=null&&!task.getDependent().equalsIgnoreCase(""))
	   {
		   depen= task.getDependent().substring(0, task.getDependent().indexOf("|"));
	      // Window.alert(depen);
	   }
		String caption ="";
	    
		a= a+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
			+open+"_,"+depen+"_,"+caption;
		return a;
		}
		Boolean checkForDrawMile(List<ProjectTaskDTO> listTask ,ProjectTaskDTO mile,ProjectTaskDTO checkData)
		{
			ProjectTaskDTO dataForMile = new ProjectTaskDTO();
			for(ProjectTaskDTO task : listTask)
			{
				if(task.getDueDate()<= mile.getStartDate())
				{
					if(dataForMile.getDueDate()!=null &&dataForMile.getDueDate()!=null)
					{
						if(task.getDueDate() > dataForMile.getDueDate())
						{
							dataForMile =task;
						}	
					}
					else
					{
						dataForMile =task;
					}
				}
			}
			
			if(dataForMile.getDueDate()!=null&&dataForMile.getDueDate()!=0 &&checkData.getTaskId() == dataForMile.getTaskId())
			{
				return true;
			}
				
			
			return false;
		}

		
		@UiHandler("button")
		void onButtonClick(ClickEvent event) {

			count = 0;
		
			ProjectTaskService.getListOrderTaskByProjectId(projectId, new AsyncCallback<List<ProjectTaskDTO>>() {
				
				@Override
				public void onSuccess(List<ProjectTaskDTO> result1) {
					LinkedList<ProjectTaskDTO> listMile = new LinkedList<ProjectTaskDTO>();
					LinkedList<ProjectTaskDTO> listTask = new LinkedList<ProjectTaskDTO>();
				
					for(ProjectTaskDTO task : result1)
					{
//						if(task.getStatus()!=3)
//						{
						
						if(task.getIsMile()==1)
						{
							listMile.add(task);
						}
						else
						{
							listTask.add(task);
						}
						//}
					}
					
					
					
					String a="";
					// TODO Auto-generated method stub
					if(listTask!=null&&listTask.size()>0)
					{
						
					for(int i = 0;i<listTask.size();i++)
					{
						if(listTask.get(i).getParentId()==0)//&&result.get(i).getStatus()!=3
						{
							
							int taskId = listTask.get(i).getTaskId();
							String taskName = listTask.get(i).getTaskName();
							String startDate = convertToDate(new Date(listTask.get(i).getStartDate()));
							String endDate = convertToDate(new Date(listTask.get(i).getDueDate()));
							String color="";
						if(listTask.get(i).getStatus()!=3)
							{
							 color ="00ffff";
							}
						else
						{
							 color ="ff0000";
						}
							
							String link ="";
							int isMile = listTask.get(i).getIsMile();
//							String res = "ducnm";
//							int comp = 60;
							
							String res = listTask.get(i).getOptAccountName();
					        Double total =listTask.get(i).getAmountOfWork();
					        Double finish = listTask.get(i).getFinishedWork();
					        Double complete=0d;
					        if(listTask.get(i).getIsMile()==0)
					        {
					        	 complete = (finish/total)*100;
							
					        }
						
							int group = listTask.get(i).getGroup();
							int parent = listTask.get(i).getParentId();
							int open =1;
							String depen ="";
							
							
						   if(listTask.get(i).getDependent()!=null&&!listTask.get(i).getDependent().equalsIgnoreCase(""))
						   {
							   depen= listTask.get(i).getDependent().substring(0, listTask.get(i).getDependent().indexOf("|"));
						      // Window.alert(depen);
						   }
							String caption ="";
							if(count==(listTask.size()-1))
							{
								a= a+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
								+open+"_,"+depen+"_,"+caption;
								count++;
								
								if(numOfMile <= listMile.size()-1&&checkForDrawMile(listTask, listMile.get(numOfMile), listTask.get(i)))
								{
									a = a+"|"+ drawRowChart(listMile.get(numOfMile));
									numOfMile++;
								}
							}

							else {
											a = a + taskId + "_," + taskName + "_,"
													+ startDate + "_," + endDate
													+ "_," + color + "_," + link
													+ "_," + isMile + "_," + res
													+ "_," + complete + "_,"
													+ group + "_," + parent + "_,"
													+ open + "_," + depen + "_,"
													+ caption + "|";
											count++;
											if(numOfMile <= listMile.size()-1&&checkForDrawMile(listTask, listMile.get(numOfMile), listTask.get(i)))
											{
												a = a+ drawRowChart(listMile.get(numOfMile))+"|";
												numOfMile++;
											}
										}
							
							
										a = drawChart(a, listTask,listMile, listTask.get(i)
												.getTaskId());
									}

								}
								smile(a);

							}

						}

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}
					});

		}


		   public String drawChart(String data,List<ProjectTaskDTO> result,List<ProjectTaskDTO> listMile,int parentId)
		   {
			   String temp="";
			   temp = data;
				for(int i = 0;i<result.size();i++)
				{
					if(result.get(i).getParentId()==parentId )
					{
						int taskId = result.get(i).getTaskId();
						String taskName = result.get(i).getTaskName();
						String startDate = convertToDate(new Date(result.get(i).getStartDate()));
						String endDate = convertToDate(new Date(result.get(i).getDueDate()));
						String color ="";
						if(result.get(i).getStatus()!=3)
						{
						 color ="00ffff";
						}
					else
					{
						 color ="ff0000";
					}
						String link ="";
						int isMile = result.get(i).getIsMile();
						String res = result.get(i).getOptAccountName();
						
				        Double total =result.get(i).getAmountOfWork();
				        Double finish = result.get(i).getFinishedWork();
				        Double complete=0d;
				        if(result.get(i).getIsMile()==0)
				        {
				        	 complete = (finish/total)*100;
						
				        }
						int group = result.get(i).getGroup();
						int parent = result.get(i).getParentId();
						int open =1;
						String depen ="";
						
						
						   if(result.get(i).getDependent()!=null&&!result.get(i).getDependent().equalsIgnoreCase(""))
						   {
							   depen= result.get(i).getDependent().substring(0, result.get(i).getDependent().indexOf("|"));
						      // Window.alert(depen);
						   }
						String caption ="";
						if(count==(result.size()-1))
						{ 
							temp= temp+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
							+open+"_,"+depen+"_,"+caption;
							if(numOfMile <= listMile.size()-1&&checkForDrawMile(result, listMile.get(numOfMile), result.get(i)))
							{
								temp = temp+"|" + drawRowChart(listMile.get(numOfMile));
								numOfMile++;
							}
							count++;
						}
						else
						{
							
							temp= temp+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
							+open+"_,"+depen+"_,"+caption+"|";
							count++;
							
							if(numOfMile <= listMile.size()-1&&checkForDrawMile(result, listMile.get(numOfMile), result.get(i)))
							{
								temp = temp+ drawRowChart(listMile.get(numOfMile))+"|" ;
								numOfMile++;
							}
						}
						if(result.get(i).getGroup()==1)
						{
							temp=drawChart(temp,result,listMile,result.get(i).getTaskId());
						}
					}
					
				}
			   
			   return temp;
			   
		   }

//	@UiHandler("button")
//	void onButtonClick(ClickEvent event) {
//
//		count = 0;
//	
//		ProjectTaskService.getListOrderTaskByProjectId(projectId, new AsyncCallback<List<ProjectTaskDTO>>() {
//			
//			@Override
//			public void onSuccess(List<ProjectTaskDTO> result1) {
//				LinkedList<ProjectTaskDTO> listMile = new LinkedList<ProjectTaskDTO>();
//				LinkedList<ProjectTaskDTO> listTask = new LinkedList<ProjectTaskDTO>();
//				for(ProjectTaskDTO task : result1)
//				{
////					if(task.getStatus()!=3)
////					{
//					listTask.add(task);
//					if(task.getIsMile()==1)
//					{
//						listMile.add(task);
//					}
//					//}
//				}
//				
//				
//				
//				String a="";
//				// TODO Auto-generated method stub
//				if(listTask!=null&&listTask.size()>0)
//				{
//					
//				for(int i = 0;i<listTask.size();i++)
//				{
//					if(listTask.get(i).getParentId()==0)//&&result.get(i).getStatus()!=3
//					{
//						
//						int taskId = listTask.get(i).getTaskId();
//						String taskName = listTask.get(i).getTaskName();
//						String startDate = convertToDate(new Date(listTask.get(i).getStartDate()));
//						String endDate = convertToDate(new Date(listTask.get(i).getDueDate()));
//						String color="";
//					if(listTask.get(i).getStatus()!=3)
//						{
//						 color ="00ffff";
//						}
//					else
//					{
//						 color ="ff0000";
//					}
//						
//						String link ="";
//						int isMile = listTask.get(i).getIsMile();
////						String res = "ducnm";
////						int comp = 60;
//						
//						String res = listTask.get(i).getOptAccountName();
//						
//				        Double total =listTask.get(i).getAmountOfWork();
//				        Double finish = listTask.get(i).getFinishedWork();
//				        Double complete=0d;
//				        if(listTask.get(i).getIsMile()==0)
//				        {
//				        	 complete = (finish/total)*100;
//						
//				        }
//					
//						int group = listTask.get(i).getGroup();
//						int parent = listTask.get(i).getParentId();
//						int open =1;
//						String depen ="";
//						
//						
//					   if(listTask.get(i).getDependent()!=null&&!listTask.get(i).getDependent().equalsIgnoreCase(""))
//					   {
//						   depen= listTask.get(i).getDependent().substring(0, listTask.get(i).getDependent().indexOf("|"));
//					      // Window.alert(depen);
//					   }
//						String caption ="";
//						if(count==(listTask.size()-1))
//						{
//							a= a+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
//							+open+"_,"+depen+"_,"+caption;
//							count++;
//
//						}
//
//						else {
//										a = a + taskId + "_," + taskName + "_,"
//												+ startDate + "_," + endDate
//												+ "_," + color + "_," + link
//												+ "_," + isMile + "_," + res
//												+ "_," + complete + "_,"
//												+ group + "_," + parent + "_,"
//												+ open + "_," + depen + "_,"
//												+ caption + "|";
//										count++;
//									}
//									a = drawChart(a, listTask, listTask.get(i)
//											.getTaskId());
//								}
//
//							}
//							smile(a);
//
//						}
//
//					}
//
//					@Override
//					public void onFailure(Throwable caught) {
//						// TODO Auto-generated method stub
//
//					}
//				});
//
//	}


//	   public String drawChart(String data,List<ProjectTaskDTO> result,int parentId)
//	   {
//		   String temp="";
//		   temp = data;
//			for(int i = 0;i<result.size();i++)
//			{
//				if(result.get(i).getParentId()==parentId )
//				{
//					int taskId = result.get(i).getTaskId();
//					String taskName = result.get(i).getTaskName();
//					String startDate = convertToDate(new Date(result.get(i).getStartDate()));
//					String endDate = convertToDate(new Date(result.get(i).getDueDate()));
//					String color ="";
//					if(result.get(i).getStatus()!=3)
//					{
//					 color ="00ffff";
//					}
//				else
//				{
//					 color ="ff0000";
//				}
//					String link ="";
//					int isMile = result.get(i).getIsMile();
//					String res = result.get(i).getOptAccountName();
//					
//			        Double total =result.get(i).getAmountOfWork();
//			        Double finish = result.get(i).getFinishedWork();
//			        Double complete=0d;
//			        if(result.get(i).getIsMile()==0)
//			        {
//			        	 complete = (finish/total)*100;
//					
//			        }
//					int group = result.get(i).getGroup();
//					int parent = result.get(i).getParentId();
//					int open =1;
//					String depen ="";
//					
//					
//					   if(result.get(i).getDependent()!=null&&!result.get(i).getDependent().equalsIgnoreCase(""))
//					   {
//						   depen= result.get(i).getDependent().substring(0, result.get(i).getDependent().indexOf("|"));
//					      // Window.alert(depen);
//					   }
//					String caption ="";
//					if(count==(result.size()-1))
//					{ 
//						temp= temp+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
//						+open+"_,"+depen+"_,"+caption;
//						count++;
//					}
//					else
//					{
//						
//						temp= temp+taskId+"_,"+taskName+"_,"+startDate+"_,"+endDate+"_,"+color+"_,"+link+"_,"+isMile+"_,"+res+"_,"+complete+"_,"+group+"_,"+parent+"_,"
//						+open+"_,"+depen+"_,"+caption+"|";
//						count++;
//					}
//					if(result.get(i).getGroup()==1)
//					{
//						temp=drawChart(temp,result,result.get(i).getTaskId());
//					}
//				}
//				
//			}
//		   
//		   return temp;
//		   
//	   }

	@UiHandler("button_1")
	void onButton_1Click(ClickEvent event) {
		PMEntrypoint.get().PMProjectDetail(projectId);
	}

	@UiHandler("btnListOfTask")
	void onBtnListOfTaskClick(ClickEvent event) {
		PMEntrypoint.get().PMCreateProjectPlan(projectId);
	}
	
	
	@UiHandler("panel")
	void onPanelAttachOrDetach(AttachEvent event) {
		
	}

	@UiHandler("btnAssignTask")
	void onBtnAssignTaskClick(ClickEvent event) {
		PMEntrypoint.get().PMAssignTask(projectId);
	}
}
